package com.blueocean_health.care.management.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blueocean_health.care.management.common.LocalManager;
import com.blueocean_health.care.management.em.LocalManagerType;

/**
 *	获取IP地址的过滤器, 继承自己的BasicFilter
 *  所有过滤器以此方式命名: 过滤顺序清晰可见
 */
@WebFilter(filterName="recordIPFilter",urlPatterns="/*") 
public class Filter01_RecordIPFilter extends BasicFilter {
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse)response;

		//记录请求的IP地址
		String ip = req.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		//放入线程变量中
		LocalManager.setVal(LocalManagerType.IP, ip);
		
		chain.doFilter(req, resp);
		
		//移除线程变量中的所有值
		LocalManager.remove();
	}
}
